﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Xml.Linq;
using System.IO;
using LinqToLfsWorld.Extensions;

namespace LinqToLfsWorld.Queries
{
	/// <summary>
	/// Queries the personal bests repository on LfsWorld.
	/// </summary>
	public class PersonalBestsQuery : LfsWorldQuery<PersonalBest>
	{

		/// <summary>
		/// Initializes a new instance of the <see cref="PersonalBestsQuery"/> class.
		/// </summary>
		/// <param name="context">The context.</param>
		public PersonalBestsQuery(LfsWorldContext context)
			: base(context)
		{
		}

		/// <summary>
		/// Gets the URL used to query LfsWorld.
		/// </summary>
		protected override string GetUrl()
		{
			string url = LfsHelper.GetPubstatUrlBase(PubstatResponseType.Xml, this, "pb");
			url += "&racer=" + (string)ExpressionValues["RacerName"].Value;

			return url;
		}

		/// <summary>
		/// Gets the entities given LfsWorld response XML
		/// </summary>
		/// <param name="responseData">The response data.</param>
		/// <returns>A collection of Host entities</returns>
		protected override IEnumerable<PersonalBest> ProcessResponse(string responseData)
		{
			XDocument doc = XDocument.Parse(responseData);

			if (doc.Root.Name == "pb_data")
			{

				var entries = doc.Descendants("entry");

				foreach (var node in entries)
				{
					PersonalBest pb = new PersonalBest();

					pb.RacerName = ((string)ExpressionValues["RacerName"].Value).StripLfsColours();
					pb.TrackIdent = node.Element("track").Value;
					pb.TrackName = Utility.CircuitNameFactory.GetNameFromIdent(pb.TrackIdent);
					pb.Car = node.Element("car").Value;
					pb.Split1 = TimeSpan.FromMilliseconds(Convert.ToInt32(node.Element("split1").Value));
					pb.Split2 = TimeSpan.FromMilliseconds(Convert.ToInt32(node.Element("split2").Value));
					pb.Split3 = TimeSpan.FromMilliseconds(Convert.ToInt32(node.Element("split3").Value));
					pb.LapTime = TimeSpan.FromMilliseconds(Convert.ToInt32(node.Element("laptime").Value));

					int ts = Convert.ToInt32(node.Element("timestamp").Value);
					pb.Timestamp = DateTimeExtensions.FromUnixTimestamp(ts);

					pb.LapCount = Convert.ToInt32(node.Element("lapcount").Value);

					yield return pb;
				}

			}

		}
	}
}
